<template>
  <div class="m-content-display">
    <Header />
    <br>
    <br>
    <br>
    <br>
    <div class="main" style="width:90%;margin-left:100px">
      <el-page-header style="margin: 10px 0 10px 0" @back="goBack" />
      <el-form ref="form" :model="form">
        <el-form-item label="标题:">
          <el-col :span="21">
            <el-input v-model="form.title" maxlength="35" show-word-limit />
          </el-col>
          <el-col :span="1" style="margin-left:20px">
            <el-button type="danger" round @click="dialogFormVisible = true">发布文章</el-button>
            <el-dialog title="发布文章" :visible.sync="dialogFormVisible">
              <el-upload
                ref="upload"
                class="upload-demo"
                drag
                action="http://localhost:8081/test/article/uploadCover"
                :limit="limit"
                :auto-upload="false"
                :on-success="uploadSuccess"
                :on-change="fileOnChange"
                :file-list="fileList"
                :data="{ folderName: 'cover' }"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <el-form :model="form">
                <el-form-item label="摘要/简介" :label-width="formLabelWidth">
                  <el-input v-model="form.description" style="height:70px" type="text" autocomplete="off" :placeholder="placeholder" />
                </el-form-item>
                <el-form-item label="文章标签" :label-width="formLabelWidth">
                  <el-tag
                    v-for="tag in dynamicTags"
                    :key="tag"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                    v-if="inputVisible"
                    ref="saveTagInput"
                    v-model="inputValue"
                    class="input-new-tag"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  />
                  <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                </el-form-item>
                <el-form-item style="margin-top:20px" label="文章类型" :label-width="formLabelWidth">
                  <el-select
                    v-model="form.articleType"
                    filterable
                    placeholder="请选择文章类型"
                    @change="handleChange"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button round @click="dialogFormVisible = false"> 取 消 </el-button>
                <el-button type="danger" round @click="submit">发 布 文 章</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-form-item>
        <el-form-item>
          <mavon-editor ref="md" v-model="form.content" class="mavonEdit" @change="handle" @imgAdd="$imgAdd" @imgDel="imgDel" />
        </el-form-item>
      </el-form>
    <!-- <article v-html="myhtml"></article> -->
    </div>
  </div>
</template>

<script>
import { publishArticle, getArticleTypeList } from '@/api/article'
import Header from '../header/index.vue'
import axios from 'axios'
export default {
  name: 'AddRelease',
  components: { Header },
  data() {
    return {
      dynamicTags: [],
      options: [],
      inputVisible: false,
      inputValue: '',
      limit: 1,
      cover: '',
      placeholder: '摘要/简介(选填)：会在推荐、列表等场景外露，帮助读者快速了解内容，如不填写，则默认抓取正文前256字符',
      form: {
        title: '',
        content: '',
        description: '',
        articleType: ''
      },
      content_html: '',
      dialogFormVisible: false,
      // myhtml: "",
      defaultData: 'preview',
      timeValue: '',
      formLabelWidth: '80px',
      fileList: []
    }
  },
  created() {},
  mounted() {
    this.getArticleTypeList()
  },
  methods: {
    fileOnChange(file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      this.loading = true
      var formdata = new FormData()
      formdata.append('file', $file)
      axios({
        url: 'http://localhost:8081/test/article/uploadCover',
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' }
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        // $vm.$img2Url 详情见本页末尾
        // 由于使用原生的axios发送请求,所以返回的res不与其他方法一样
        this.$refs.md.$img2Url(pos, res.data.data)
      })
      this.loading = false
    },
    imgDel() {

    },
    uploadSuccess(responese, file, fileList) {
      this.cover = responese.data
      var articleTagsStr = ''
      if (this.dynamicTags.length === 1) {
        articleTagsStr = this.dynamicTags[0]
      } else {
        this.dynamicTags.forEach((element) => {
          articleTagsStr += element + ','
        })
        articleTagsStr = articleTagsStr.substring(0, articleTagsStr.length - 1)
      }
      publishArticle({ title: this.form.title, description: this.form.description,
        content: this.content_html, userId: this.$store.state.user.id, articleTypeId: this.form.articleType,
        cover: this.cover, articleTags: articleTagsStr }).then(res => {
        this.dialogFormVisible = false
        this.$message({
          type: 'success',
          message: '文章发布成功'
        })
        this.$router.replace('/index')
      })
    },
    handleChange() {
      console.log(this.form.articleType)
    },
    handle(value, render) {
      // console.log(render)
      this.content_html = render
      // console.log(this.form.content)
    },
    submit() {
      if (this.form.title === '') {
        this.$message.error('标题不能为空')
        return
      }
      if (this.form.content === '') {
        this.$message.error('内容不能为空')
        return
      }
      if (this.form.description === '') {
        this.form.description = this.form.content.slice(0, 35)
      }
      // 封装文章类型ids并添加自定义的文章类型
      if (this.form.articleType === '') {
        this.$message({
          type: 'info',
          message: '文章类型未填!'
        })
        return
      }
      if (this.dynamicTags.length === 0) {
        this.$message({
          type: 'info',
          message: '至少需要为文章添加一个标签'
        })
      }
      if (this.fileList.length === 0) {
        this.$message({
          type: 'info',
          message: '文章封面未上传!无法发布文章'
        })
      }
      // this.form.articleType.forEach(element => {
      //   if (typeof element === 'string') {
      //     addArticleType({ name: element }).then(res => {
      //       console.log(res)
      //       articleTypeIds += res.data.id + ','
      //       console.log(articleTypeIds)
      //     })
      //   } else {
      //     articleTypeIds += element + ','
      //   }
      // })
      this.$refs.upload.submit()
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    goBack() {
      this.$router.back()
    },
    getArticleTypeList() {
      getArticleTypeList().then(res => {
        this.options = res.data.list
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.m-content-display {
    display: flex;
    flex-direction: column;
    min-height: 100%;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .mavonEdit {
    height: 700px;
    z-index: 0;
  }
</style>
